<?
	function db_connect()
	{
		$con = mysql_connect(DBHOST,DBUSER,DBPASS);
		if(!$con)
		{
			echo 'Can not connect database.';
		}
		else
		{
			if(!mysql_select_db(DBNAME,$con))
			{
				echo 'Can not select database.';
				$con = db_close($con);
			}
			else
			{
				mysql_query("Set character_set_connection=utf8");
				mysql_query("Set character_set_results=utf8");
				mysql_query("Set character_set_client=utf8");
			}
		}
		
		return $con;
	}
	
	function db_close($con)
	{
		$con2 = mysql_close($con);
		return $con2;
	}
	
	function utf8_to_tis620($string)
	{
		$str = $string;
		$res = "";
		for ($i = 0; $i < strlen($str); $i++) {
		  if (ord($str[$i]) == 224) {
			$unicode = ord($str[$i+2]) & 0x3F;
			$unicode |= (ord($str[$i+1]) & 0x3F) << 6;
			$unicode |= (ord($str[$i]) & 0x0F) << 12;
			$res .= chr($unicode-0x0E00+0xA0);
			$i += 2;
		  } else {
			$res .= $str[$i];
		  }
		}
		return $res;
	}
	
	function br2nl($string)
	{
		$string = str_replace('<br />','',$string);
		return preg_replace('/\<br(\s*)?\/?\>/i', "\n", $string);
	} 
	
	function browser_info($agent=null) {
		// Declare known browsers to look for
		$known = array('ms ie', 'firefox', 'safari', 'webkit', 'opera', 'netscape',
		'konqueror', 'gecko');

		// Clean up agent and build regex that matches phrases for known browsers
		// (e.g. "Firefox/2.0" or "MSIE 6.0" (This only matches the major and minor
		// version numbers.  E.g. "2.0.0.6" is parsed as simply "2.0"
		$agent = strtolower($agent ? $agent : $_SERVER['HTTP_USER_AGENT']);
		$pattern = '#(?<browser>' . join('|', $known) .
		')[/ ]+(?<version>[0-9]+(?:\.[0-9]+)?)#';

		// Find all phrases (or return empty array if none found)
		if (!preg_match_all($pattern, $agent, $matches)) return array();

		// Since some UAs have more than one phrase (e.g Firefox has a Gecko phrase,
		// Opera 7,8 have a MSIE phrase), use the last one found (the right-most one
		// in the UA).  That's usually the most correct.
		$i = count($matches['browser'])-1;
		return array($matches['browser'][$i] => $matches['version'][$i]);
	}
?>